import { bindActionCreators } from 'redux'
import { connect } from 'react-redux'
import * as CustomerBirthdayAction from '../actions/customerBirthday'
import forEach from 'lodash/forEach'
import isEmpty from 'lodash/isEmpty'

import { WeaTable } from 'comsRedux'

const WeaTableAction = WeaTable.action;
 import WeaFormmodeTop from './WeaFormmodeTop'
import { WeaSearchGroup,WeaRightMenu, WeaPopoverHrm,WeaSelect} from 'ecCom'

import {WeaErrorPage,WeaTools} from 'ecCom'

import {Button,Form,Modal,message} from 'antd' 
const createForm = Form.create;
const FormItem = Form.Item;

import cloneDeep from 'lodash/cloneDeep'
import objectAssign from 'object-assign'

import PropTypes from 'react-router/lib/PropTypes'
import Immutable from 'immutable'
const is = Immutable.is;

let _this = null;

class CustomerBirthday extends React.Component {
    constructor(props) {
		super(props);
		_this = this;
    }
    componentDidMount() {
    	 const {actions} = this.props;
         actions.setNowRouterCmpath('customerBirthday');
         actions.doSearch();
         actions.initDatas();

    }
    componentWillReceiveProps(nextProps) {
        const keyOld = this.props.location.key;
        const keyNew = nextProps.location.key;
        if(keyOld!==keyNew) {
            const {actions} = this.props;
            actions.doSearch();
            actions.initDatas();
   
        }
    }
    shouldComponentUpdate(nextProps,nextState) {
        return !is(this.props.title,nextProps.title)||
        !is(this.props.dataKey,nextProps.dataKey)||
        !is(this.props.conditioninfo,nextProps.conditioninfo)||
        !is(this.props.showSearchAd,nextProps.showSearchAd)||
        !is(this.props.searchParamsAd,nextProps.searchParamsAd)||
        !is(this.props.loading,nextProps.loading)||
        !is(this.props.comsWeaTable,nextProps.comsWeaTable);
    }
    render() {
        let that = this;
        const {loading,comsWeaTable,actions,title,dataKey,showSearchAd,searchParamsAd} = this.props;
        const name = dataKey ? dataKey.split('_')[0] : 'init';
        const loadingTable = comsWeaTable.get(name).toJS().loading;
        const selectedRowKeys = comsWeaTable.get('selectedRowKeys');
        return (
            <div className="crm-top-req">
            	<WeaRightMenu datas={this.getRightMenu()} onClick={this.onRightMenuClick.bind(this)}>
                <WeaFormmodeTop
                	title={title}
                	loading={loading || loadingTable}
                	icon={<i className='icon-coms-crm' />}
                	iconBgcolor='#96358a'
                	buttons={[]}
                    buttonSpace={10}
                	showDropIcon={true}
                	dropMenuDatas={this.getRightMenu()}
                	onDropMenuClick={this.onRightMenuClick.bind(this)}
                    buttonsAd={this.getTabButtonsAd()}
                    searchType={['base','advanced']}
                    searchsBaseValue={searchParamsAd.get('firstName')}
                    setShowSearchAd={bool=>{actions.setShowSearchAd(bool)}}
                    hideSearchAd={()=> actions.setShowSearchAd(false)}
                    searchsAd={<Form horizontal>{this.getSearchs()}</Form>}
                    showSearchAd={showSearchAd}
                    onSearch={v=>{actions.doSearch()}}
                    onSearchChange={v=>{actions.saveOrderFields({firstName:{name:'firstName',value:v}})}}
                >
                    <WeaTable 
                        sessionkey={dataKey}
                    	hasOrder={true}
                        needScroll={true}
                        onOperatesClick={this.onOperatesClick.bind(this)}
                    />
                </WeaFormmodeTop>
                </WeaRightMenu>
            </div>
        )
    }
    onRightMenuClick(key){
    	 const {actions,comsWeaTable,dataKey} = this.props;
    	if(key == '0'){
    		actions.doSearch();
    		actions.setShowSearchAd(false);
    	}
    	if(key == '1'){
    		actions.setColSetVisible(dataKey,true);
    		actions.tableColSet(dataKey,true)
    	}
    }
    getRightMenu(){
    	let btns = [];
    	btns.push({
    		icon: <i className='icon-coms-search'/>,
            content:'搜索',
            key:0
    	});
    	btns.push({
    		icon: <i className='icon-coms-Custom '/>,
            content:'显示定制列',
            key:1
    	})
    	return btns
    }
    getSearchs() {
        const { conditioninfo } = this.props;
        const {getFieldProps} = this.props.form;
        let group = [];
		conditioninfo && conditioninfo.toJS().map(c =>{
			let items = [];
			c.items.map(field => {
                if(field.formItemType == "MONTH_DAY"){
                    items.push({
                        com:(<FormItem
                            label={`${field.label}`}
                            labelCol={{span: `${field.labelcol}`}}
                            wrapperCol={{span: `${field.fieldcol}`}}>
                            <div style={{width: 120,display:"inline-block"}}>
                                <WeaSelect {...getFieldProps(field.domkey[0], {
                                    initialValue:this.getSelectDefaultValue(this.createMonth())})} options={this.createMonth()} style={{width: 120}}/>
                            </div>
                            <div style={{width: 120,display:"inline-block",marginLeft:10}}>
                                <WeaSelect {...getFieldProps(field.domkey[1], {
                                    initialValue:""})} options={this.createDate()} style={{width: 120}} />
                            </div>
                            </FormItem>),
                        colSpan:1
                    })
                }else{
                    items.push({
                        com:(<FormItem
                            label={`${field.label}`}
                            labelCol={{span: `${field.labelcol}`}}
                            wrapperCol={{span: `${field.fieldcol}`}}>
                                { WeaTools.getComponent(field.formItemType, field.browserConditionParam, field.domkey, this.props, field)}
                            </FormItem>),
                        colSpan:1
                    })
                }
            });
			group.push(<WeaSearchGroup needTigger={true} title={c.title} showGroup={c.defaultshow} items={items}/>)
		});
		return group
    }
   
    getTabButtonsAd() {
    	const {actions} = this.props;
        return [
            (<Button type="primary" onClick={()=>{actions.doSearch();actions.setShowSearchAd(false)}}>搜索</Button>),
            (<Button type="ghost" onClick={()=>{actions.saveOrderFields({})}}>重置</Button>),
            (<Button type="ghost" onClick={()=>{actions.setShowSearchAd(false)}}>取消</Button>)
        ]
    }
    onOperatesClick=(record,index,operate,flag)=>{
        // console.log(record,index,operate,flag)
 
     }
     createMonth(){
         let monthOptions =[];
         const nowMonth = new Date().getMonth()+1;
         for(let i=1;i<13;i++){
            monthOptions.push({
                "key": i+"",
                "selected": nowMonth==i ? true:false,
                "showname": i+"月"
            })
         }
         return monthOptions;
     }
     createDate(){
        let dateOptions =[];
        for(let i=1;i<32;i++){
            dateOptions.push({
               "key": i+"",
               "selected": false,
               "showname": i<10 ? "0"+i : i
           })
        }
        dateOptions.unshift({ "key": "","selected": true,"showname":""})
        return dateOptions;
    }
    getSelectDefaultValue = (options) => {
        let value = '';
        forEach(options, (option) => {
            if(option.selected){
                value = option.key;
            }
        })
        return value;
    }
}



class MyErrorHandler extends React.Component {
    render(){
        const hasErrorMsg = this.props.error && this.props.error!=="";
        return (
            <WeaErrorPage msg={hasErrorMsg?this.props.error:"对不起，该页面异常，请联系管理员！"} />
        );
    }
}

CustomerBirthday = WeaTools.tryCatch(React, MyErrorHandler, {error: ""})(CustomerBirthday);

CustomerBirthday = createForm({
	onFieldsChange(props, fields) {
        props.actions.saveOrderFields({...props.orderFields.toJS(), ...fields});
    },
	mapPropsToFields(props) {
		return props.orderFields.toJS();
  	}
})(CustomerBirthday);

function mapStateToProps(state) {
	const {crmcustomerBirthday,comsWeaTable} = state;
    return  {
    	loading: crmcustomerBirthday.get('loading'),
        title: crmcustomerBirthday.get('title'),
         dataKey: crmcustomerBirthday.get('dataKey'),
         conditioninfo: crmcustomerBirthday.get('conditioninfo'),
         showSearchAd: crmcustomerBirthday.get('showSearchAd'),
        searchParamsAd: crmcustomerBirthday.get('searchParamsAd'),
        orderFields:crmcustomerBirthday.get('orderFields'),
		//table
        comsWeaTable: comsWeaTable, //绑定整个table
    }
}

function mapDispatchToProps(dispatch) {
    return {
        actions: bindActionCreators({...CustomerBirthdayAction,...WeaTableAction}, dispatch)
    }
}

export default connect(mapStateToProps, mapDispatchToProps)(CustomerBirthday);
